<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>🔍 质检慧眼 - 工业智能质检平台</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet">
    
    <!-- 配置Tailwind自定义颜色 -->
    <script>
        tailwind.config = {
            theme: {
                extend: {
                    colors: {
                        primary: '#165DFF', // 专业蓝：主色调
                        secondary: '#36D399', // 成功绿：辅助色
                        warning: '#FBBD23', // 警告黄
                        danger: '#F87272', // 危险红
                        neutral: '#64748B', // 中性灰
                    },
                    fontFamily: {
                        sans: ['Inter', 'system-ui', 'sans-serif'],
                    }
                }
            }
        }
    </script>
    
    <style type="text/tailwindcss">
        @layer utilities {
            .content-auto {
                content-visibility: auto;
            }
            .card-hover {
                transition: all 0.3s ease;
            }
            .card-hover:hover {
                transform: translateY(-5px);
                box-shadow: 0 10px 25px -5px rgba(0, 0, 0, 0.1), 0 10px 10px -5px rgba(0, 0, 0, 0.04);
            }
            .btn-primary {
                @apply bg-primary text-white py-3 px-6 rounded-lg font-semibold transition-all duration-300 hover:bg-primary/90 hover:shadow-lg;
            }
            .input-field {
                @apply w-full px-4 py-3 rounded-lg border border-gray-300 focus:border-primary focus:ring-2 focus:ring-primary/20 transition-all duration-200;
            }
        }
    </style>
</head>
<body class="bg-gray-50 font-sans text-gray-800">
    <div class="container mx-auto px-4 py-8 max-w-7xl">
        <!-- 页面头部 -->
        <header class="text-center mb-10">
            <div class="inline-block bg-primary text-white p-4 rounded-full shadow-lg mb-4">
                <i class="fa fa-search-plus text-3xl"></i>
            </div>
            <h1 class="text-[clamp(1.8rem,4vw,2.5rem)] font-bold text-primary mb-3">质检慧眼</h1>
            <p class="text-neutral text-lg max-w-2xl mx-auto">AI驱动的工业质检平台，精准识别产品缺陷，提升质量控制效率</p>
        </header>
        
        <!-- 主内容区 -->
        <div class="grid grid-cols-1 lg:grid-cols-3 gap-8 mb-10">
            <!-- 左侧：质检参数设置 -->
            <div class="lg:col-span-1">
                <div class="bg-white rounded-xl shadow-md p-6 h-full">
                    <h2 class="text-xl font-bold text-primary mb-5 flex items-center">
                        <i class="fa fa-cogs mr-2"></i>质检参数
                    </h2>
                    
                    <form id="inspectionForm" class="space-y-6">
                        <!-- 产品类型 -->
                        <div>
                            <label for="productType" class="block text-sm font-medium text-gray-700 mb-1">产品类型 *</label>
                            <select id="productType" class="input-field" required>
                                <option value="电子元件">电子元件</option>
                                <option value="机械零件">机械零件</option>
                                <option value="塑料产品">塑料产品</option>
                                <option value="金属制品">金属制品</option>
                                <option value="纺织品">纺织品</option>
                                <option value="包装产品">包装产品</option>
                            </select>
                        </div>
                        
                        <!-- 关注缺陷类型 -->
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-2">关注缺陷类型 (可多选) *</label>
                            <div id="defectsContainer" class="space-y-2">
                                <!-- 由JavaScript动态填充 -->
                            </div>
                        </div>
                        
                        <!-- 产品描述 -->
                        <div>
                            <label for="description" class="block text-sm font-medium text-gray-700 mb-1">产品描述 (可选)</label>
                            <textarea id="description" rows="3" class="input-field" placeholder="请描述产品的基本情况、生产工艺、已知问题等..."></textarea>
                        </div>
                        
                        <!-- 图片上传 -->
                        <div>
                            <label class="block text-sm font-medium text-gray-700 mb-1">上传产品图片 (可选)</label>
                            <div class="mt-1 flex justify-center px-6 pt-5 pb-6 border-2 border-gray-300 border-dashed rounded-lg">
                                <div class="space-y-1 text-center">
                                    <i class="fa fa-picture-o text-3xl text-gray-400 mb-2"></i>
                                    <div class="flex text-sm text-gray-600">
                                        <label for="imageUpload" class="relative cursor-pointer bg-white rounded-md font-medium text-primary hover:text-primary/80">
                                            <span>选择图片</span>
                                            <input id="imageUpload" name="image" type="file" accept="image/*" class="sr-only">
                                        </label>
                                        <p class="pl-1">或拖放图片</p>
                                    </div>
                                    <p class="text-xs text-gray-500">支持 JPG、PNG、WEBP 等格式</p>
                                </div>
                            </div>
                            <div id="imagePreview" class="mt-2 hidden">
                                <img id="previewImg" src="" alt="产品图片预览" class="max-w-full h-40 object-contain rounded-lg border">
                                <button type="button" id="removeImage" class="mt-1 text-sm text-red-500 hover:text-red-700">
                                    <i class="fa fa-times mr-1"></i> 移除图片
                                </button>
                            </div>
                        </div>
                        
                        <!-- 分析按钮 -->
                        <div class="pt-4">
                            <button type="submit" id="analyzeBtn" class="btn-primary w-full flex items-center justify-center">
                                <i class="fa fa-line-chart mr-2"></i> 开始质检分析
                            </button>
                        </div>
                    </form>
                </div>
            </div>
            
            <!-- 右侧：分析结果 -->
            <div class="lg:col-span-2 space-y-6">
                <!-- 加载状态 -->
                <div id="loading" class="bg-white rounded-xl shadow-md p-8 text-center hidden">
                    <div class="inline-block animate-spin rounded-full h-12 w-12 border-t-2 border-b-2 border-primary mb-4"></div>
                    <p class="text-gray-600">正在进行AI质检分析，请稍候...</p>
                </div>
                
                <!-- 错误信息 -->
                <div id="errorMessage" class="bg-red-50 border-l-4 border-red-400 p-4 rounded-r-lg hidden">
                    <div class="flex">
                        <div class="flex-shrink-0">
                            <i class="fa fa-exclamation-circle text-red-500"></i>
                        </div>
                        <div class="ml-3">
                            <p class="text-sm text-red-700" id="errorText"></p>
                        </div>
                    </div>
                </div>
                
                <!-- 分析结果 -->
                <div id="resultArea" class="bg-white rounded-xl shadow-md overflow-hidden hidden">
                    <div class="bg-primary text-white p-4 flex justify-between items-center">
                        <h2 class="text-xl font-bold flex items-center">
                            <i class="fa fa-check-circle mr-2"></i> 质检分析结果
                        </h2>
                        <button id="copyResultBtn" class="bg-white text-primary px-4 py-2 rounded-lg text-sm font-medium hover:bg-gray-100 transition-all-300">
                            <i class="fa fa-copy mr-1"></i> 复制结果
                        </button>
                    </div>
                    <div class="p-6">
                        <div id="resultContent" class="prose max-w-none">
                            <!-- 分析结果将在这里显示 -->
                        </div>
                    </div>
                </div>
                
                <!-- 功能说明 -->
                <div class="bg-white rounded-xl shadow-md p-6">
                    <h3 class="font-bold text-lg text-primary mb-4 flex items-center">
                        <i class="fa fa-info-circle mr-2"></i>质检慧眼的核心能力
                    </h3>
                    <div class="grid grid-cols-1 md:grid-cols-2 gap-4">
                        <div class="flex">
                            <div class="flex-shrink-0 h-10 w-10 flex items-center justify-center rounded-full bg-primary/10 text-primary">
                                <i class="fa fa-eye"></i>
                            </div>
                            <div class="ml-3">
                                <h4 class="text-sm font-medium text-gray-900">缺陷精准识别</h4>
                                <p class="text-xs text-gray-500 mt-1">自动识别各类产品表面和结构缺陷，准确率高</p>
                            </div>
                        </div>
                        <div class="flex">
                            <div class="flex-shrink-0 h-10 w-10 flex items-center justify-center rounded-full bg-primary/10 text-primary">
                                <i class="fa fa-bolt"></i>
                            </div>
                            <div class="ml-3">
                                <h4 class="text-sm font-medium text-gray-900">高速检测</h4>
                                <p class="text-xs text-gray-500 mt-1">比人工检测快10倍以上，大幅提升生产效率</p>
                            </div>
                        </div>
                        <div class="flex">
                            <div class="flex-shrink-0 h-10 w-10 flex items-center justify-center rounded-full bg-primary/10 text-primary">
                                <i class="fa fa-bar-chart"></i>
                            </div>
                            <div class="ml-3">
                                <h4 class="text-sm font-medium text-gray-900">质量分析</h4>
                                <p class="text-xs text-gray-500 mt-1">提供缺陷原因分析和生产改进建议</p>
                            </div>
                        </div>
                        <div class="flex">
                            <div class="flex-shrink-0 h-10 w-10 flex items-center justify-center rounded-full bg-primary/10 text-primary">
                                <i class="fa fa-database"></i>
                            </div>
                            <div class="ml-3">
                                <h4 class="text-sm font-medium text-gray-900">数据积累</h4>
                                <p class="text-xs text-gray-500 mt-1">持续学习改进，随着使用提升检测精度</p>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 适用场景 -->
        <div class="bg-white rounded-xl shadow-md p-6 mb-10">
            <h2 class="text-xl font-bold text-primary mb-6 text-center">适用场景</h2>
            <div class="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-6">
                <div class="border border-gray-100 rounded-lg p-5 card-hover">
                    <div class="text-primary text-2xl mb-3"><i class="fa fa-microchip"></i></div>
                    <h3 class="font-bold text-lg mb-2">电子制造业</h3>
                    <p class="text-gray-600 text-sm">PCB板检测、电子元件外观检测、焊接质量检测</p>
                </div>
                <div class="border border-gray-100 rounded-lg p-5 card-hover">
                    <div class="text-primary text-2xl mb-3"><i class="fa fa-cogs"></i></div>
                    <h3 class="font-bold text-lg mb-2">机械加工</h3>
                    <p class="text-gray-600 text-sm">零部件尺寸检测、表面质量检测、装配完整性检测</p>
                </div>
                <div class="border border-gray-100 rounded-lg p-5 card-hover">
                    <div class="text-primary text-2xl mb-3"><i class="fa fa-industry"></i></div>
                    <h3 class="font-bold text-lg mb-2">汽车制造</h3>
                    <p class="text-gray-600 text-sm">车身检测、零部件检测、装配质量检测</p>
                </div>
                <div class="border border-gray-100 rounded-lg p-5 card-hover">
                    <div class="text-primary text-2xl mb-3"><i class="fa fa-shopping-bag"></i></div>
                    <h3 class="font-bold text-lg mb-2">包装行业</h3>
                    <p class="text-gray-600 text-sm">包装完整性检测、标签检测、印刷质量检测</p>
                </div>
                <div class="border border-gray-100 rounded-lg p-5 card-hover">
                    <div class="text-primary text-2xl mb-3"><i class="fa fa-scissors"></i></div>
                    <h3 class="font-bold text-lg mb-2">纺织行业</h3>
                    <p class="text-gray-600 text-sm">面料缺陷检测、印染质量检测、缝纫质量检测</p>
                </div>
                <div class="border border-gray-100 rounded-lg p-5 card-hover">
                    <div class="text-primary text-2xl mb-3"><i class="fa fa-flask"></i></div>
                    <h3 class="font-bold text-lg mb-2">医疗器械</h3>
                    <p class="text-gray-600 text-sm">精密部件检测、洁净度检测、装配质量检测</p>
                </div>
            </div>
        </div>
        
        <!-- 页脚 -->
        <footer class="text-center text-gray-500 text-sm py-6">
            <p>质检慧眼 &copy; 2025 | 工业智能质检平台</p>
            <p class="mt-2">免责声明：本工具提供的分析结果仅供参考，最终质量判断请结合专业人员意见</p>
        </footer>
    </div>

    <script>
        // 产品类型对应的缺陷列表
        const PRODUCT_DEFECTS = {
            "电子元件": ["外观损伤", "尺寸偏差", "焊接不良", "引脚变形", "标识错误"],
            "机械零件": ["表面划痕", "裂纹", "变形", "毛刺", "装配错误"],
            "塑料产品": ["气泡", "色差", "缩水", "飞边", "断裂"],
            "金属制品": ["锈蚀", "凹陷", "划痕", "镀层缺陷", "变形"],
            "纺织品": ["断线", "污渍", "色差", "针脚不齐", "瑕疵"],
            "包装产品": ["密封不良", "标签错误", "破损", "印刷错误", "尺寸不符"]
        };

        // DOM元素
        const productType = document.getElementById('productType');
        const defectsContainer = document.getElementById('defectsContainer');
        const description = document.getElementById('description');
        const imageUpload = document.getElementById('imageUpload');
        const imagePreview = document.getElementById('imagePreview');
        const previewImg = document.getElementById('previewImg');
        const removeImage = document.getElementById('removeImage');
        const inspectionForm = document.getElementById('inspectionForm');
        const analyzeBtn = document.getElementById('analyzeBtn');
        const loading = document.getElementById('loading');
        const errorMessage = document.getElementById('errorMessage');
        const errorText = document.getElementById('errorText');
        const resultArea = document.getElementById('resultArea');
        const resultContent = document.getElementById('resultContent');
        const copyResultBtn = document.getElementById('copyResultBtn');

        // 初始化缺陷选项
        function initDefects() {
            const type = productType.value;
            defectsContainer.innerHTML = '';
            
            PRODUCT_DEFECTS[type].forEach(defect => {
                const label = document.createElement('label');
                label.className = 'flex items-center';
                
                const checkbox = document.createElement('input');
                checkbox.type = 'checkbox';
                checkbox.className = 'form-checkbox h-4 w-4 text-primary rounded';
                checkbox.name = 'defects';
                checkbox.value = defect;
                checkbox.checked = true; // 默认全选
                
                const span = document.createElement('span');
                span.className = 'ml-2 text-sm text-gray-700';
                span.textContent = defect;
                
                label.appendChild(checkbox);
                label.appendChild(span);
                defectsContainer.appendChild(label);
            });
        }

        // 处理图片上传预览
        imageUpload.addEventListener('change', function(e) {
            const file = e.target.files[0];
            if (file) {
                const reader = new FileReader();
                reader.onload = function(e) {
                    previewImg.src = e.target.result;
                    imagePreview.classList.remove('hidden');
                };
                reader.readAsDataURL(file);
            }
        });

        // 移除图片
        removeImage.addEventListener('click', function() {
            imageUpload.value = '';
            imagePreview.classList.add('hidden');
            previewImg.src = '';
        });

        // 产品类型变化时更新缺陷选项
        productType.addEventListener('change', initDefects);

        // 表单提交处理
        inspectionForm.addEventListener('submit', async function(e) {
            e.preventDefault();
            
            // 获取选中的缺陷类型
            const selectedDefects = Array.from(
                document.querySelectorAll('input[name="defects"]:checked')
            ).map(cb => cb.value);
            
            if (selectedDefects.length === 0) {
                showError('请至少选择一种关注的缺陷类型');
                return;
            }
            
            // 准备表单数据
            const formData = new FormData();
            formData.append('product_type', productType.value);
            formData.append('description', description.value);
            
            // 添加选中的缺陷
            selectedDefects.forEach(defect => {
                formData.append('defects', defect);
            });
            
            // 添加图片（如果有）
            if (imageUpload.files.length > 0) {
                formData.append('file', imageUpload.files[0]);
            }
            
            // 显示加载状态
            showLoading();
            
            try {
                // 发送请求
                const response = await fetch('/api/analyze', {
                    method: 'POST',
                    body: formData
                });
                
                const result = await response.json();
                
                if (response.ok && result.success) {
                    // 显示结果
                    resultContent.innerHTML = result.result
                        .replace(/\n/g, '<br>')
                        .replace(/### (.*?)/g, '<h3 class="text-lg font-bold mt-4 mb-2">$1</h3>')
                        .replace(/## (.*?)/g, '<h2 class="text-xl font-bold mt-6 mb-3">$1</h2>');
                    showResult();
                } else {
                    throw new Error(result.error || '质检分析失败，请重试');
                }
            } catch (error) {
                console.error('分析错误:', error);
                showError(error.message);
            }
        });

        // 复制结果
        copyResultBtn.addEventListener('click', function() {
            const text = resultContent.textContent;
            
            navigator.clipboard.writeText(text).then(() => {
                const originalText = copyResultBtn.innerHTML;
                copyResultBtn.innerHTML = '<i class="fa fa-check mr-1"></i> 已复制';
                copyResultBtn.classList.add('bg-green-500');
                copyResultBtn.classList.remove('bg-white', 'text-primary');
                
                setTimeout(() => {
                    copyResultBtn.innerHTML = originalText;
                    copyResultBtn.classList.remove('bg-green-500');
                    copyResultBtn.classList.add('bg-white', 'text-primary');
                }, 2000);
            }).catch(err => {
                console.error('复制失败:', err);
                alert('复制失败，请手动复制');
            });
        });

        // 显示加载状态
        function showLoading() {
            loading.classList.remove('hidden');
            errorMessage.classList.add('hidden');
            resultArea.classList.add('hidden');
            analyzeBtn.disabled = true;
            analyzeBtn.innerHTML = '<i class="fa fa-spinner fa-spin mr-2"></i> 分析中...';
        }

        // 显示错误信息
        function showError(message) {
            errorText.textContent = message;
            errorMessage.classList.remove('hidden');
            loading.classList.add('hidden');
            resultArea.classList.add('hidden');
            analyzeBtn.disabled = false;
            analyzeBtn.innerHTML = '<i class="fa fa-line-chart mr-2"></i> 开始质检分析';
        }

        // 显示分析结果
        function showResult() {
            resultArea.classList.remove('hidden');
            loading.classList.add('hidden');
            errorMessage.classList.add('hidden');
            analyzeBtn.disabled = false;
            analyzeBtn.innerHTML = '<i class="fa fa-line-chart mr-2"></i> 开始质检分析';
            
            // 滚动到结果区域
            resultArea.scrollIntoView({ behavior: 'smooth' });
        }

        // 页面加载时初始化
        window.addEventListener('load', initDefects);
    </script>
</body>
</html>
